package com.xiang.community.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author qixiangLi
 * @Date 2021/11/15
 */
@Component
@Slf4j
public class RedisUtil {
    private static final String SPLIT = ":";
    @Resource
    private JedisPool jedisPool;

    public void saveIntoSet(String prefix, Object key, Object value) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.sadd(prefix + SPLIT + key, value.toString());
        }
    }

    public void removeFromSet(String prefix, Object key, Object value) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.srem(prefix + SPLIT + key, value.toString());
        }
    }

    public boolean isMemberOfSet(String prefix, Object key, Object value) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.sismember(prefix + SPLIT + key, value.toString());
        }
    }

    public Set<String> getValuesFromSet(String prefix, Object key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.smembers(prefix + SPLIT + key);
        }
    }

    public void saveIntoString(String prefix, Object key, Object value) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(prefix + SPLIT + key, value.toString());
        }
    }

    public String getValueFromString(String prefix, Object key) {
        if (key == null) {
            return null;
        }

        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.get(prefix + SPLIT + key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void removeFromRedis(String prefix, String token) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.del(prefix + SPLIT + token);
        }
    }
}
